import { readdirSync } from 'fs';
import { Inject, Injectable, Optional } from '@nestjs/common';
import path from 'path';

@Injectable()
export class ConfigService {
  constructor(@Inject('config_options') options: { path: string }, @Optional() private config = {}) {
    // const options = { path: path.resolve(__dirname, '../configure') };
    readdirSync(options.path).map(async (file) => {
      if (file.slice(-2) === 'js') {
        const module = await import(path.resolve(options.path, file));
        this.config = { ...this.config, ...module.default() };
      }
    });
  }
  get(path: string) {
    return path.split('.').reduce((config, name) => {
      return config[name];
    }, this.config);
  }
}
